/**
 * Copyright (c) 2011 Paul Wagner
 */
package com.pew.tasktimer.runner;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import com.pew.tasktimer.domain.Task;
import com.pew.tasktimer.domain.TaskTimerPackage;
import com.pew.tasktimer.domain.report.Report;
import com.pew.tasktimer.domain.report.ReportSumation;
import com.pew.tasktimer.store.JAXBStore;
import com.pew.util.PropertyConfig;

/**
 * @author Elwin
 * Created: Mar 24, 2011
 * Purpose: 
 *
 */
public class TaskTimerStart {

	static Logger cLogger = Logger.getLogger(TaskTimerStart.class);
	static String cStrFilePath=PropertyConfig.getProperty("file.storage.path");
	static String cStrFilePathReport=PropertyConfig.getProperty("file.report.storage.path");
	static String cStrFilePathReportXsl=PropertyConfig.getProperty("file.report.xsl.path");
	
	public void startTimer() {
		Task lTask = new Task();
		lTask.startTimer();
		
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		
		if (lTTP == null) {
			lTTP = new TaskTimerPackage();
		}
		
		lTTP.stopRunningTasks();  // clean-up running tasks first.
		lTTP.addTask(lTask);
		JAXBStore.storeXml(lTTP, cStrFilePath);
	}
	
	public Task stopTimerReturn() {
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		if (lTTP == null) {
			lTTP = new TaskTimerPackage();
			cLogger.warn("Cannot read from file; first use of program?");
			return null;
		}
		//MANTIS: may not stop the desired one because it picks up the first;
		Task lTask = lTTP.getLatestRunningTask();
		lTask.stopTimer();
		lTTP.stopRunningTasks();  //MANTIS: cleanup
		JAXBStore.storeXml(lTTP, cStrFilePath);
		return lTask;
	}
	
	public Task[] getTasks() {
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		if (lTTP == null) {
			lTTP = new TaskTimerPackage();
			cLogger.warn("Cannot read from file; first use of program?");
		}
		else
		{
			return lTTP.getTasks();
		}
		
		return null;
	}
	
	public void storeChanges(Task myTask){
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		if(lTTP != null)
		{
			if(lTTP.storeThisTask(myTask))
			{
				cLogger.info("Task was new.");
			}
			else
			{
				cLogger.info("Task already existed.");
			}
		}
		else
		{
			lTTP = new TaskTimerPackage();
			lTTP.addTask(myTask);
		}
		
		JAXBStore.storeXml(lTTP, cStrFilePath);
	}
	
	public void stopTimerNC() {
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		if (lTTP == null) {
			lTTP = new TaskTimerPackage();
			cLogger.warn("Cannot read from file; first use of program?");
			return;
		}
		//MANTIS: may not stop the desired one because it picks up the first;
		Task lTask = lTTP.getLatestRunningTask();
		lTask.stopTimer();
		lTTP.stopRunningTasks();  //MANTIS: cleanup
		JAXBStore.storeXml(lTTP, cStrFilePath);
	}
	
	public void stopTimerSimpleC() {
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		if (lTTP == null) {
			lTTP = new TaskTimerPackage();
			cLogger.warn("Cannot read from file; first use of program?");
			return;
		}
		
		Task lTask = lTTP.getLatestRunningTask();
		if(lTask == null)
		{
			if (cLogger.isDebugEnabled()) {
				cLogger.debug("No timer running.  Nothing to stop.");
			}
			return;
		}
		lTask.stopTimer();
		String myNote = JOptionPane.showInputDialog("Enter a note.\nNotes and projects can be set with \":\" deminator.");
		String lStr[] = myNote.split(":");
		if(lStr != null && lStr.length > 1)
		{
			if (cLogger.isDebugEnabled()) {
				cLogger.debug("Project found: " + lStr[1].trim());
			}
			lTask.setcStrProject(lStr[1].trim());
		}
		
		lTask.setcStrNote(myNote);
		lTTP.stopRunningTasks();  //MANTIS cleanup
		JAXBStore.storeXml(lTTP, cStrFilePath);
	}
	
	/**
	 * Stop the latest timer and ask for information (note, projects, tags);
	 * then start the next.  Good for fast entry.
	 */
	public void restartTimerSimpleC()
	{
		stopTimerSimpleC();
		startTimer();
	}
	
	/**
	 * Generate a report and store it using a style sheet.
	 */
	public void reportXml() {
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		ReportSumation lReportSum = Report.generateReport(lTTP.getTasks());
		JAXBStore.transformAndStore(lReportSum, cStrFilePathReportXsl, cStrFilePathReport);
	}
	
	public void fixXml() {
		TaskTimerPackage lTTP = JAXBStore.readXmlPackage(cStrFilePath);
		lTTP.setUniqueIDs();
		JAXBStore.storeXml(lTTP, cStrFilePath);
	}
	
	public String getReportFileLocation()
	{
		return cStrFilePathReport;
	}
	
	public static void printHelp() {
		
		InputStream in = ClassLoader.getSystemResourceAsStream("help.txt");
		OutputStream out = System.out;
	     int nextChar;
	     try {
		     while ( ( nextChar = in.read() ) != -1  )
		     {
			     out.write((char) nextChar);
			     
		     }
		     out.write( '\n' );
		     out.flush();
		     in.close();
		     out.close();
	     }catch(Exception ex) {
	    	 ex.printStackTrace();
	     }
		
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		if (cLogger.isDebugEnabled()) {
			cLogger.debug("Received args: " + args.toString());
		}
		
		if(args.length > 0)
		{
			TaskTimerStart lTTS = new TaskTimerStart();
			if(args[0].equals("start")){
				lTTS.startTimer();
			}
			else if(args[0].equals("stopgc"))
			{
				lTTS.stopTimerSimpleC();
			}
			else if(args[0].equals("restartgc")){
				lTTS.restartTimerSimpleC();
			}
			else if(args[0].equals("report")) {
				lTTS.reportXml();
					
			}
			else if(args[0].equals("fix")) {
				lTTS.fixXml();
			}
			else {
				printHelp();
			}
		}
		else {
			printHelp();
		}
		
		
		
	}
}
